package my;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class QQServer {

	public static void start() throws IOException, ClassNotFoundException {
		// 1.启动一个ServerSocket服务，监听9999端口
		ServerSocket ss = new ServerSocket(9999);
		while (true) {
			// 2.接收客户端连接
			Socket socket = ss.accept();
			// 3.获取socket到jvm的输入流
			InputStream is = socket.getInputStream();
			// 4.封装一个对象的输入流
			ObjectInputStream ois = new ObjectInputStream(is);
			// 5.读取请求参数对象
			Object readObject = ois.readObject();
			QQRequest request = (QQRequest) readObject;
			//System.out.println("用户名：" + request.getUsername() + "====密码：" + request.getPassword());
			// 6.写入本地文件
			QQResponse response = operator(request);
			// 7.返回客户端一个响应结果
			// 8.获取socket输出流
			OutputStream outputStream = socket.getOutputStream();
			// 9.将socket原生输出流封装为对象输出流方便直接写对象
			ObjectOutputStream oos = new ObjectOutputStream(outputStream);
			// 10.将注册响应结果通过socket传给客户端
			oos.writeObject(response);
			oos.flush();
		}
	}

	private static QQResponse operator(QQRequest request) throws IOException {
		QQResponse response = new QQResponse();
		Integer operator = request.getOperator();
		if(operator == 1){//如果是注册
			File file = new File("F:\\QQFiles\\" + request.getUsername());
			if (file.exists()) {
				System.out.println("用户：" + request.getUsername() + "已注册！");
				response.setSuccess(false);
				response.setMsg("注册失败，用户已存在");
			} else {
				file.mkdirs();//创建用户文件夹(加了S之后方法可以强制创建多级文件夹)
				File file1 = new File("F:\\QQFiles\\" + request.getUsername() + "\\account.txt");
				FileWriter fw = new FileWriter(file1);
				fw.write(request.getUsername() + "#" + request.getPassword());
				fw.flush();
				fw.close();
				response.setSuccess(true);
				response.setMsg("注册成功");
			}
		}else if(operator == 2){//如果是登录
			File file = new File("F:\\QQFiles\\" + request.getUsername() + "\\account.txt");
			if(file.exists()){
				FileReader fr = new FileReader(file);
				BufferedReader br = new BufferedReader(fr);//包装字符流，使用readLine
				String str = br.readLine();
				String username = str.split("#")[0];//根据#号切割字符串获取到用户名和密码 例如：315055923#abc1234
				String password = str.split("#")[1];//根据#号切割字符串获取到用户名和密码
				if(username.equals(request.getUsername()) && password.equals(request.getPassword())){
					response.setSuccess(true);
					response.setMsg("登录成功，爽！");
					//登录成功，加载好友信息
					loadFriendsInfo(request, response);
				}else{
					response.setSuccess(false);
					response.setMsg("登录失败，帐号或密码错误，不爽！");
				}
			}else{
				response.setSuccess(false);
				response.setMsg("登录失败，请先注册");
			}
		}else if(operator == 3){//添加好友
			//1.校验用户是否拥有QQ帐号
			boolean flag = false;
			flag = checkUserExists(request, flag);
			if(!flag){
				response.setSuccess(false);
				response.setMsg("你要添加的好友不存在，请检查你的输入是否正确！");
				return response;
			}
			//2.锁定当前登录用户的好友文件，如果该文件不存在，说明是第一次添加好友，需要创建文件并写入第一个好友信息
			File file = new File("F:\\QQFiles\\" + request.getUsername() + "\\friends.txt");
			if(file.exists()){
				//如果存在好友文件，说明已经有添加好友，读取好友文件，获取好友列表，判断当前要添加的好友是否是已存在
				BufferedReader br = new BufferedReader(new FileReader(file));
				String s = br.readLine();
				String[] friends = s.split("#");
				//校验好友是否存在
				boolean flag1 = false;
				flag1 = checkFriendExists(request,friends, flag1);
				if(flag1){
					response.setSuccess(false);
					response.setMsg("你已添加该好友！");
					return response;
				}
				br.close();//写文件之前把读关掉，防止读写冲突导致程序异常
				FileWriter fw = new FileWriter(file);
				fw.write(s + "#" + request.getFriend());
				fw.flush();
				fw.close();
				response.setSuccess(true);
				response.setMsg("添加成功");
				return response;
			}else{
				file.createNewFile();
				FileWriter fw = new FileWriter(file);
				fw.write(request.getFriend());
				fw.flush();
				fw.close();
				response.setSuccess(true);
				response.setMsg("添加成功");
				return response;
			}
		}else if(operator == 4) {//查询好友列表
			loadFriendsInfo(request, response);
			response.setSuccess(true);
			response.setMsg("加载好友列表成功");
		}else if(operator == 5) {//查询好友列表

		}
		return response;
	}

	private static void loadFriendsInfo(QQRequest request, QQResponse response) throws IOException {
		File friendFile = new File("F:\\QQFiles\\" + request.getUsername() + "\\friends.txt");
		if(friendFile.exists()){
            BufferedReader br1 = new BufferedReader(new FileReader(friendFile));
            String[] friends = br1.readLine().split("#");
            response.setFriends(friends);
            br1.close();
        }
	}


	private static boolean checkFriendExists(QQRequest request, String[] friends, boolean flag1) {
		String friend = request.getFriend();
		for(String fr : friends){
			if(friend.equals(fr)){
				return true;
			}
		}
		return false;
	}

	private static boolean checkUserExists(QQRequest request, boolean flag) {
		String friend = request.getFriend();
		File file = new File("F:\\QQFiles");
		File[] files = file.listFiles();
		System.out.println("当前系统拥有的用户：");
		for(File f : files){
            if(friend.equals(f.getName())){
                flag = true;
                break;
            }
        }
		return flag;
	}

	private static boolean ifFriendExists(QQRequest request) {
		boolean friendExists = false;
		File dir = new File("F:\\QQFiles\\");
		File[] users = dir.listFiles();
		for(File f : users){
            if(f.getName().equals(request.getFriend())){
                friendExists = true;
            }
        }
		return friendExists;
	}

	public static void main(String[] args) throws IOException, ClassNotFoundException {
		start();
	}

}
